package com.brillilab.service.logic.instrument;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.exceptions.BrillilabException;
import com.brillilab.domain.vo.lab.LabMemberVo;
import com.brillilab.service.quartz.BrillQuartzScheduler;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.instrument.AppointmentStateEnum;
import com.brillilab.domain.enums.instrument.CancelTypeEnum;
import com.brillilab.domain.enums.instrument.InstrumentStateEnum;
import com.brillilab.domain.enums.lab.LabMemberEnum;
import com.brillilab.domain.enums.lab.LabMemberPowerEnum;
import com.brillilab.domain.po.instrument.*;
import com.brillilab.domain.po.lab.Lab;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.user.Users;
import com.brillilab.domain.vo.instrument.InstrumSearchVo;
import com.brillilab.domain.vo.instrument.InstrumentTo;
import com.brillilab.domain.vo.instrument.InstrumentVo;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.constant.JobConstants;
import com.brillilab.service.core.instrument.*;
import com.brillilab.service.core.lab.ILabMemberPowerService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.lab.ILabService;
import com.brillilab.service.logic.instrument.converter.InstrumentConverter;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.service.module.message.producer.MessageProducer;
import com.brillilab.service.module.message.template.impl.instrument.AppointmentCancelTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class InstrumentLogic {

    @Resource
    private IInstrumentService instrumentService;
    @Resource
    private IInstrumentMaintenanceService maintenanceService;
    @Resource
    private IInstrumentAppointmentService appointmentService;

    @Resource
    private ILabService labService;
    @Resource
    private ILabMemberService labMemberService;
    @Resource
    private ILabMemberPowerService labMemberPowerService;
    @Resource
    private UsersLogic usersLogic;
    @Autowired
    private BrillQuartzScheduler quartzScheduler;
    @Resource
    private IInstrumentAccessGroupService accessGroupService;
    @Resource
    private IInstrumentAccessMemberService accessMemberService;

    @Resource
    private MessageProducer messageProducer;

    /**
     * 仪器搜索业务
     *
     * @param searchVo
     * @param userInfo
     * @return
     */
    public PageVo<InstrumentVo> searchForInstrument(InstrumSearchVo searchVo,UserInfoVo userInfo) {

        int pageNum = searchVo.getPageNum()!=null && searchVo.getPageNum() >0 ? searchVo.getPageNum() : 1;
        int pageSize = searchVo.getPageSize()!=null && searchVo.getPageSize()>0 ? searchVo.getPageSize() : 10;

        //查询参数封装
        LambdaQueryWrapper<Instrument> wrapper=new LambdaQueryWrapper<>();

        if(userInfo.getLabId() != null)
            wrapper.eq(Instrument::getLabId,userInfo.getLabId());
        if(searchVo.getState().equals(InstrumentStateEnum.STOP_USE.getValue()) || searchVo.getState().equals(InstrumentStateEnum.NORMAL.getValue()))
            wrapper.eq(Instrument::getState,searchVo.getState());
        if(searchVo.getState().equals(InstrumentStateEnum.MAINTENANCE.getValue()))
            wrapper.eq(Instrument::getState,InstrumentStateEnum.NORMAL.getValue());

        wrapper.like(Instrument::getName,searchVo.getName());
        wrapper.eq(Instrument::getIsDelete,BoolEnum.FALSE.getValue());

        //设置管理者的查询参数
        setManagersWrapper(searchVo.isManager(),userInfo,wrapper);

        //查询记录
        List<InstrumentTo> instrumentTos=getInstrumentToList(userInfo,searchVo.isManager(),wrapper);

        //对象转换
        List<InstrumentVo> instrumentVos=InstrumentConverter.instrumentToListInstrumentVoList(instrumentTos);

        //查询不同状态仪器时筛选
        instrumentVos=filteringDifferentStatus(searchVo,instrumentVos);

        List<InstrumentVo> finalList = instrumentVos.size()>pageSize ? instrumentVos.subList(0,pageSize) : instrumentVos;

        //分页参数
        PageVo<InstrumentVo> instrumentVoPageVo=new PageVo<>(pageNum,pageSize,instrumentVos.size(),finalList);

        return instrumentVoPageVo;
    }


    //查询不同状态仪器时筛选
    private List<InstrumentVo> filteringDifferentStatus(InstrumSearchVo searchVo,List<InstrumentVo> instrumentVos) {
        //正常
        if(InstrumentStateEnum.NORMAL.getValue().equals(searchVo.getState())){
            ArrayList<InstrumentVo> nomalList=new ArrayList<>();
            for (InstrumentVo e : instrumentVos) {
                if(InstrumentStateEnum.NORMAL.getValue().equals(e.getState())){
                    nomalList.add(e);
                }
            }
            instrumentVos=nomalList;
        }
        //维护
        if(InstrumentStateEnum.MAINTENANCE.getValue().equals(searchVo.getState())){
            ArrayList<InstrumentVo> maintanList=new ArrayList<>();
            for (InstrumentVo e : instrumentVos) {
                if(InstrumentStateEnum.MAINTENANCE.getValue().equals(e.getState())){
                    maintanList.add(e);
                }
            }
            instrumentVos=maintanList;
        }
        return instrumentVos;
    }

    //设置管理者的查询参数
    private void setManagersWrapper(Boolean isManager,UserInfoVo userInfo,LambdaQueryWrapper<Instrument> wrapper) {
        //管理者
        if(isManager){
            //所有者
            if(labMemberService.isOwner(userInfo.getLabId(),userInfo.getLabMemberId())){
                return;
            }
            //管理员
            if(labMemberPowerService.isPower(userInfo.getLabId(),userInfo.getLabMemberId(),LabMemberPowerEnum.Power.INSTRUMENT_MANAGE)){
                return;
            }
            //负责人 是则查询对应的仪器
            List<Long> dutyIds=instrumentService.selectDuties(userInfo.getLabId());
            for (Long dutyid : dutyIds) {
                if(dutyid.equals(userInfo.getId())){
                    wrapper.eq(Instrument::getDutyId,userInfo.getId());
                    return;
                }
            }
            //无权限
            wrapper.eq(Instrument::getDutyId,0);
        }
    }

    /**
     * 查询所有仪器对应的负责人ID
     *
     * @param labid
     * @return
     */
    public List<Long> selectDuties(Long labid) {
        return instrumentService.selectDuties(labid);
    }

    /**
     * 仪器分页
     *
     * @return
     */
    public PageVo<InstrumentTo> getInstrumentPage(UserInfoVo userInfo,Boolean isManager,Integer pageNum,Integer pageSize,Integer total,LambdaQueryWrapper<Instrument> wrapper) {

        pageNum = pageNum!=null && pageNum >0 ? pageNum : 1;
        pageSize = pageSize!=null && pageSize>0 ? pageSize : 10;

        //分页查询
        Page<Instrument> page=new Page<>(pageNum,pageSize);

        IPage<Instrument> instrumentsPage=instrumentService.selectPage(page,wrapper);

        List<Instrument> instruments=instrumentsPage.getRecords();

        List<LabMemberVo> labMemberVos=labMemberService.selectByLabId(userInfo.getLabId());

        instruments.forEach(e -> {
            LabMemberVo labMemberVo=labMemberVos.stream().filter(u -> u.getUserId().equals(e.getDutyId())).findFirst().orElse(null);
            if(labMemberVo!=null){
                e.setDutyName(labMemberVo.getUserName());
            }
        });

        List<InstrumentTo> instrumentTos=new ArrayList<InstrumentTo>();


        // 不是管理员看到所有仪器但不可使用非自己的
        if(!isManager){
            //预约页面
            for (Instrument e : instruments) {
                InstrumentTo instrumentTo=new InstrumentTo();

                Long groupId=e.getAccessGroupId();
                boolean usable=false;

                //duty
                usable=isManagerAndDuty(e.getDutyId(),userInfo);

                if(groupId != null && groupId != 0){
                    List<InstrumentAccessMember> accessMembers=accessMemberService.selectList(groupId);

                    for (InstrumentAccessMember accessMember : accessMembers) {
                        if(accessMember.getLabMemberId().equals(userInfo.getLabMemberId())){
                            usable=true;
                            break;
                        }
                    }
                } else {
                    usable=true;
                }

                instrumentTo.setUsable(usable);

                putAppointmentAndMaitenanceIntoPo(instrumentTos,e,instrumentTo);
            }

        } else {
            //是管理页面
            for (Instrument e : instruments) {
                List<LabMember> labMembers=new ArrayList<>();
                InstrumentTo instrumentTo=new InstrumentTo();
                Long groupId=e.getAccessGroupId();
                if(groupId != null && groupId != 0){
                    List<InstrumentAccessMember> accessMembers=accessMemberService.selectList(groupId);
                    List<Long> labMemberIds=accessMembers.stream().map(InstrumentAccessMember::getLabMemberId).distinct().collect(Collectors.toList());
                    List<LabMember> allMembers=labMemberService.selectList(labMemberIds);
                    for (InstrumentAccessMember accessMember : accessMembers) {
                        LabMember labmember=allMembers.stream().filter(m -> m.getId().equals(accessMember.getLabMemberId())).findFirst().orElse(null);
                        if(labmember != null){
                            labMembers.add(labmember);
                        }
                    }
                    instrumentTo.setIsAll(false);
                } else {
                    labMembers=labMemberService.selectPoList(userInfo.getLabId(),LabMemberEnum.State.STATE_IN.getValue());
                    instrumentTo.setIsAll(true);
                }
                instrumentTo.setLabMembers(labMembers);
                putAppointmentAndMaitenanceIntoPo(instrumentTos,e,instrumentTo);
            }
        }


        PageVo<InstrumentTo> instrumentToPageVo=new PageVo<InstrumentTo>(pageNum,pageSize,total,instrumentTos);

        return instrumentToPageVo;
    }

    /**
     * 仪器列表
     *
     * @return
     */
    public List<InstrumentTo> getInstrumentToList(UserInfoVo userInfo,Boolean isManager,LambdaQueryWrapper<Instrument> wrapper) {

        //分页查询
        List<Instrument> instruments=instrumentService.selectList(wrapper);

        List<InstrumentTo> instrumentTos=new ArrayList<InstrumentTo>();


        // 不是管理员看到所有仪器但不可使用非自己的
        if(!isManager){
            //预约页面
            for (Instrument e : instruments) {
                InstrumentTo instrumentTo=new InstrumentTo();

                Long groupId=e.getAccessGroupId();
                boolean usable=false;

                //duty
                usable=isManagerAndDuty(e.getDutyId(),userInfo);

                if(groupId != null && groupId != 0){
                    List<InstrumentAccessMember> accessMembers=accessMemberService.selectList(groupId);

                    for (InstrumentAccessMember accessMember : accessMembers) {
                        if(accessMember.getLabMemberId().equals(userInfo.getLabMemberId())){
                            usable=true;
                            break;
                        }
                    }
                } else {
                    usable=true;
                }

                instrumentTo.setUsable(usable);

                putAppointmentAndMaitenanceIntoPo(instrumentTos,e,instrumentTo);
            }

        } else {
            //是管理页面
            for (Instrument e : instruments) {
                List<LabMember> labMembers=new ArrayList<>();
                InstrumentTo instrumentTo=new InstrumentTo();
                Long groupId=e.getAccessGroupId();
                if(groupId != null && groupId != 0){
                    List<InstrumentAccessMember> accessMembers=accessMemberService.selectList(groupId);
                    List<Long> labMemberIds=accessMembers.stream().map(InstrumentAccessMember::getLabMemberId).distinct().collect(Collectors.toList());
                    List<LabMember> allMembers=labMemberService.selectList(labMemberIds);
                    for (InstrumentAccessMember accessMember : accessMembers) {
                        LabMember labmember=allMembers.stream().filter(m -> m.getId().equals(accessMember.getLabMemberId())).findFirst().orElse(null);
                        if(labmember != null){
                            labMembers.add(labmember);
                        }
                    }
                    instrumentTo.setIsAll(false);
                } else {
                    labMembers=labMemberService.selectPoList(userInfo.getLabId(),LabMemberEnum.State.STATE_IN.getValue());
                    instrumentTo.setIsAll(true);
                }
                instrumentTo.setLabMembers(labMembers);
                putAppointmentAndMaitenanceIntoPo(instrumentTos,e,instrumentTo);
            }
        }

        return instrumentTos;
    }

    //用户是否是管理员或责任人
    public boolean isManagerAndDuty(Long dutyId,UserInfoVo userInfo) {
        if(labMemberService.isOwner(userInfo.getLabId(),userInfo.getLabMemberId())){
            return true;
        }

        if(labMemberPowerService.isPower(userInfo.getLabId(),userInfo.getLabMemberId(),LabMemberPowerEnum.Power.INSTRUMENT_MANAGE)){
            return true;
        }

        if(dutyId.equals(userInfo.getId())){
            return true;
        }

        return false;
    }

    //查出预约和维护信息
    private void putAppointmentAndMaitenanceIntoPo(List<InstrumentTo> instrumentTos,Instrument instrument,InstrumentTo instrumentTo) {
        instrumentTo.setInstrument(instrument);
        //获取最近三次预约
        List<InstrumentAppointment> appointments=appointmentService.selectTopThree(instrument.getId(),AppointmentStateEnum.NOT_START.getValue(),AppointmentStateEnum.START.getValue());
        instrumentTo.setAppointments(appointments);

        //获取维护信息
        List<InstrumentMaintenance> maintenances=maintenanceService.selectList(instrument.getId());
        instrumentTo.setMaintenances(maintenances);

        instrumentTos.add(instrumentTo);
    }

    /**
     * 新增仪器
     * @param instrumentVo
     * @param userInfoVo
     * @return
     */
    public Instrument createNewInstrument(InstrumentVo instrumentVo,UserInfoVo userInfoVo) {

        //是否有权限修改
        if(!isManagerAndDuty(instrumentVo.getDutyId(),userInfoVo)){
            throw new BrillilabException(ResultEnum.USER_NOT_POWER);
        }

        //负责人
        Users user=usersLogic.getUser(instrumentVo.getDutyId());
        Assert.notNull(user,"负责人不存在！");

        instrumentVo.setDutyName(user.getName());
        instrumentVo.setLabId(userInfoVo.getLabId());
        instrumentVo.setLabName(userInfoVo.getLabName());

        //参数转换
        InstrumentTo instrumentTo;
        instrumentTo=InstrumentConverter.instrumentVoToInstrumentTo(instrumentVo);

        Instrument instrument=instrumentTo.getInstrument();

        //核对实验室信息是否存在
        Lab lab=labService.selectById(instrument.getLabId());
        Assert.notNull(lab,"实验室不存在！");
        Assert.isTrue(lab.getId().equals(userInfoVo.getLabId()),"用户无法添加仪器到其他实验室！");

        List<LabMember> labMembers=labMemberService.selectPoList(userInfoVo.getLabId(),LabMemberEnum.State.STATE_IN.getValue());
        List<Long> labMemberIdsAll=labMembers.stream().map(LabMember::getId).distinct().collect(Collectors.toList());

        //新增使用成员列表
        Long[] labMemberIds=instrumentTo.getLabMemberIds();
        InstrumentAccessGroup group=null;
        if(labMemberIds != null && labMemberIds.length != 0){
            group=new InstrumentAccessGroup();
            group.setState(BoolEnum.TRUE.getValue());
            accessGroupService.insert(group);

            List<InstrumentAccessMember> accessMembers=new ArrayList<>();
            for (Long labMemberId : labMemberIds) {
                Assert.isTrue(labMemberIdsAll.contains(labMemberId),"责任人不属于该实验室！");
                InstrumentAccessMember accessMember=new InstrumentAccessMember();
                accessMember.setLabMemberId(labMemberId);
                accessMember.setAccessGroupId(group.getId());
                accessMembers.add(accessMember);
            }
            accessMemberService.insertBatch(accessMembers);
        }

        //核对仪器是否存在（按仪器编号）
        Instrument exist=instrumentService.selectOne(userInfoVo.getLabId(),instrument.getNo());
        Assert.isNull(exist,"仪器编号已使用！");

        //添加glistid
        if(group != null){
            instrument.setAccessGroupId(group.getId());
        }

        //插入仪器数据
        instrumentService.insert(instrument);

        return instrument;
    }

    /**
     * 仪器信息回显
     *
     * @return
     */
    public InstrumentTo recallInstrument(Long instrumentId,Long labId) {
        InstrumentTo instrumentTo=new InstrumentTo();

        //查找Instrument
        Instrument instrument=instrumentService.selectById(instrumentId);
        Assert.notNull(instrument,"仪器不存在！");
        Assert.isTrue(instrument.getLabId().equals(labId),"仪器不属于该实验室！");

        instrumentTo.setInstrument(instrument);


        //查找maintenance
        List<InstrumentMaintenance> maintenances=maintenanceService.selectList(instrumentId);
        if(!CollectionUtils.isEmpty(maintenances)){
            instrumentTo.setMaintenances(maintenances);
        }

        return instrumentTo;
    }

    /**
     * 仪器列表
     *
     * @param pageNum
     * @param pageSize
     * @param isManager
     * @param userInfo
     * @return
     */
    public PageVo<InstrumentVo> getInstrumentList(Integer pageNum,Integer pageSize,Boolean isManager,UserInfoVo userInfo) {
        LambdaQueryWrapper<Instrument> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Instrument::getIsDelete,BoolEnum.FALSE.getValue());

        if(userInfo.getLabId() != null){
            wrapper.eq(Instrument::getLabId,userInfo.getLabId());
        }

        //设置管理者的查询参数
        setManagersWrapper(isManager,userInfo,wrapper);

        //查询记录条数
        Integer total=instrumentService.selectCount(wrapper);

        //查找仪器列表
        PageVo<InstrumentTo> instrumentToPage=getInstrumentPage(userInfo,isManager,pageNum,pageSize,total,wrapper);

        //对象转换
        List<InstrumentVo> instrumentVos=InstrumentConverter.instrumentToListInstrumentVoList(instrumentToPage.getContent());

        PageVo<InstrumentVo> instrumentVoPageVo=new PageVo<>(instrumentToPage.getPageNum(),instrumentToPage.getPageSize(),instrumentToPage.getTotalRow(),instrumentVos);

        return instrumentVoPageVo;
    }

    /**
     * 更新仪器
     *
     * @param instrumentTo
     */
    public Instrument modifyInstrument(InstrumentTo instrumentTo,UserInfoVo userInfo) {

        Instrument instrument=instrumentTo.getInstrument();

        //核对是否存在
        Instrument exist=instrumentService.selectById(instrument.getId());
        Assert.notNull(exist,"仪器不存在！");

        List<LabMember> labMembers=labMemberService.selectPoList(userInfo.getLabId(),LabMemberEnum.State.STATE_IN.getValue());
        List<Long> labMemberIdsAll=labMembers.stream().map(LabMember::getId).distinct().collect(Collectors.toList());

        //是否有权限修改
        if(!isManagerAndDuty(instrument.getDutyId(),userInfo)){
            throw new BrillilabException(ResultEnum.USER_NOT_POWER);
        }

        //是否停用 （停用取消所有未开始和已开始预约）
        if(InstrumentStateEnum.STOP_USE.getValue().equals(instrument.getState())){
            if(InstrumentStateEnum.NORMAL.getValue().equals(exist.getState())){
                List<InstrumentAppointment> appointments=appointmentService.selectList(instrument.getId(),InstrumentStateEnum.STOP_USE.getValue(),InstrumentStateEnum.NORMAL.getValue());

                if(!CollectionUtils.isEmpty(appointments)){
                    log.info("取消所有未开始和已开始预约");
                    for (InstrumentAppointment appointment : appointments) {
                        appointment.setState(AppointmentStateEnum.CANCEL.getValue());
                        appointment.setUpdateTime(new Date());
                        appointment.setCancelReason(CancelTypeEnum.OFF_SERVICE_CANCEL.getValue());
                        appointmentService.updateById(appointment);
                        //TODO 通知预约取消
                        sendCancelAppointmentMessage(CancelTypeEnum.ADMIN_CANCEL.getValue(),userInfo,instrument,appointment);
                    }
                }
            }
        }

        //修改可使用人名单
        if(instrumentTo.getLabMemberIds() != null && instrumentTo.getLabMemberIds().length > 0){
            Long[] labMemberIds=instrumentTo.getLabMemberIds();

            if(exist.getAccessGroupId() != null && exist.getAccessGroupId() != 0){
                //存在，删除，添加
                InstrumentAccessGroup group=accessGroupService.selectById(exist.getAccessGroupId());
                accessMemberService.delete(group.getId());

                List<InstrumentAccessMember> accessMembers = new ArrayList<>();
                for (Long labMemberId : labMemberIds) {
                    Assert.isTrue(labMemberIdsAll.contains(labMemberId),"责任人不属于该实验室！");
                    InstrumentAccessMember accessMember=new InstrumentAccessMember();
                    accessMember.setAccessGroupId(group.getId());
                    accessMember.setLabMemberId(labMemberId);
                    accessMembers.add(accessMember);
                }
                accessMemberService.insertBatch(accessMembers);
            } else {
                //不存在，添加
                InstrumentAccessGroup group=new InstrumentAccessGroup();
                group.setState(1);
                accessGroupService.insert(group);

                List<InstrumentAccessMember> accessMembers = new ArrayList<>();
                for (Long labMemberId : labMemberIds) {
                    Assert.isTrue(labMemberIdsAll.contains(labMemberId),"责任人不属于该实验室！");
                    InstrumentAccessMember accessMember=new InstrumentAccessMember();
                    accessMember.setAccessGroupId(group.getId());
                    accessMember.setLabMemberId(labMemberId);
                    accessMembers.add(accessMember);
                }
                accessMemberService.insertBatch(accessMembers);

                instrument.setAccessGroupId(group.getId());
            }

        } else {
            instrument.setAccessGroupId(0L);
        }

        //更新仪器
        instrumentService.updateById(instrument);

        return instrumentService.selectById(instrument.getId());
    }

    @Async
    public void sendCancelAppointmentMessage(Integer cancelType,UserInfoVo userInfo,Instrument instrument,InstrumentAppointment appointment) {

        UserInfoVo apUser=usersLogic.getUserInfo(userInfo.getLabId(),appointment.getUserId());
        Assert.notNull(apUser,"仪器预约用户不存在于该实验室！");

        AppointmentCancelTemplate appointmentCancelTemplate=new AppointmentCancelTemplate(cancelType,instrument,appointment,userInfo);
        messageProducer.sendMessagePush(appointmentCancelTemplate);
    }

    /**
     * 删除仪器
     *
     * @param instrumId
     */
    public boolean getInstrumentDelete(Long instrumId,UserInfoVo userInfoVo) {

        Instrument instrument=instrumentService.selectById(instrumId);
        Assert.isTrue(instrument!=null && instrument.getIsDelete().equals(BoolEnum.FALSE.getValue()),"仪器不存在！");
        Assert.isTrue(instrument.getLabId().equals(userInfoVo.getLabId()),"仪器不属于该实验室！");

        //（1）判断仪器是否存在预约，如果存在删除所有预约
        findAppointmentDelete(instrument,userInfoVo);

        //（2）删除仪器的所有维护
        findMaintenacesDelete(instrumId);

        //（3）删除仪器(更新删除状态为1)
        deleteInstrument(instrument);


        return true;

    }

    //找到仪器预约删除
    private void findAppointmentDelete(Instrument instrument,UserInfoVo userInfo){
        List<InstrumentAppointment> appointments=appointmentService.selectList(instrument.getId());

        if(!CollectionUtils.isEmpty(appointments)){
            for (InstrumentAppointment appointment : appointments) {

                //取消预约
                appointment.setState(AppointmentStateEnum.CANCEL.getValue());
                appointment.setCancelReason(CancelTypeEnum.ADMIN_CANCEL.getValue());
                appointmentService.updateById(appointment);

                //删除定时任务
                quartzScheduler.deleteJob(JobConstants.JOB_GROUP_APPOINTMENT_START + appointment.getId(),JobConstants.JOB_GROUP_APPOINTMENT_START);
                quartzScheduler.deleteJob(JobConstants.JOB_GROUP_APPOINTMENT_END + appointment.getId(),JobConstants.JOB_GROUP_APPOINTMENT_END);
                log.info("取消预约ID:" + appointment.getId());

                //TODO 通知所有仪器预约者仪器被删除，预约被取消
                sendCancelAppointmentMessage(CancelTypeEnum.ADMIN_CANCEL.getValue(),userInfo,instrument,appointment);
                log.info("通知所有仪器预约者仪器被删除，预约被取消");
            }
        }
    }

    //找到仪器维护删除
    private void findMaintenacesDelete(Long instrumId) {
        maintenanceService.deleteByInstrumentId(instrumId);
    }

    //删除仪器
    private void deleteInstrument(Instrument instrument) {
        instrument.setIsDelete(BoolEnum.TRUE.getValue());
        instrumentService.updateById(instrument);
    }

    /**
     * 是否可用仪器
     * @param instrumId
     * @param userInfo
     * @return
     */
    public boolean canUse(Long instrumId,UserInfoVo userInfo) {

        Instrument instrument=instrumentService.selectById(instrumId);
        Assert.notNull(instrument,"仪器不存在！");

        Boolean isManager=isManagerAndDuty(instrument.getDutyId(),userInfo);

        if(isManager){
            return true;
        } else {
            Long groupId=instrument.getAccessGroupId();

            if(groupId != null && groupId != 0){
                List<InstrumentAccessMember> accessMembers=accessMemberService.selectList(groupId);

                for (InstrumentAccessMember accessMember : accessMembers) {
                    if(accessMember.getLabMemberId().equals(userInfo.getLabMemberId())){
                        return true;
                    }
                }
            }else {
                return false;
            }
        }
        return false;
    }
}
